package com.zzz.offer.printmatrix;

import java.util.ArrayList;

public class PrintMatrix {

    public static void main(String[] args) {
        int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
        System.out.println(new PrintMatrix().printMatrix(array));
    }

    public ArrayList<Integer> printMatrix(int[][] matrix) {

        if (matrix.length == 0 || matrix[0].length == 0) {
            return null;
        }

        ArrayList<Integer> list = new ArrayList<>();

        int[][] flag = new int[matrix.length][matrix[0].length];
        // 处理四种转折的方式

        int i = 0, j = -1;
        int count = 0;
        while (count < matrix.length * matrix[0].length) {

            // 从左边向右边移动一列需要 j++
            j++;
            while (j < matrix[0].length && flag[i][j] == 0) {
                flag[i][j] = 1;
                list.add(matrix[i][j++]);
                count++;
            }
            j--;

            // 换下一行，所以 i 要加一
            i++;
            while (i < matrix.length && flag[i][j] == 0) {
                flag[i][j] = 1;
                list.add(matrix[i++][j]);
                count++;
            }
            i--;

            // 从右边向左移一列  要j--
            j--;
            while (j >= 0 && flag[i][j] == 0) {
                flag[i][j] = 1;
                list.add(matrix[i][j--]);
                count++;
            }
            j++;

            // 从下向上移一行 要 i--
            i--;
            while (i >= 0 && flag[i][j] == 0) {
                flag[i][j] = 1;
                list.add(matrix[i--][j]);
                count++;
            }
            i++;

        }

        return list;
    }
}
